package com.tim.app.ui.activity.selected;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.application.library.log.DLOG;
import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.ClickUtil;
import com.application.library.util.KeyboardChangeListener;
import com.application.library.util.StringUtil;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.MyTextWatch.MyTextWatcher;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.ImagePickerManager;
import com.tim.app.server.api.API_App;
import com.tim.app.server.entry.InputContent;
import com.tim.app.server.entry.Problem;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.UploadResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.view.LSWebView;
import com.tim.app.ui.widget.imagepick.bean.ImageItem;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;


/**
 * 提问页面
 */
public class AskQuestionActivity extends BaseActivity implements KeyboardChangeListener.KeyBoardListener {

    private static final String TAG = "AskQuestionActivity";
    private EditText et_title;
    private String title;
    private TextView tvTitle;
    private LinearLayout ll_content;
    private TextView tvCancel;
    private TextView tvNext;

    private final int MIN_TITLE = 4;
    private final int MIN_TITLE_BYTE = 2 * MIN_TITLE;

    private boolean isEditProblem;//编辑问题
    private Problem problem;

    private ImageButton ibKeyboard, ib_picture, ibAt;
    private ImagePickerManager imagePicker;
    private LSWebView lsContent;
    private ImageButton ibSetting;

    private LinearLayout llBottomContainer;
    private LinearLayout llActionBottom;
    private TextView tvAnonymousState;
    private ImageButton ibAnonymous;
    private KeyboardChangeListener mKeyboardChangeListener;

    private boolean isAnonymous = false;

    /**
     * 编辑问题
     *
     * @param context
     * @param data
     */
    public static void startWithEditProblem(Activity context, Problem data) {
        Intent intent = new Intent(context, AskQuestionActivity.class);
        intent.putExtra(AppKey.PROBLEM, data);
        intent.putExtra("isEditProblem", true);
        context.startActivity(intent);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_ask_question;
    }

    @Override
    public void initView() {
        ll_content = (LinearLayout) findViewById(R.id.ll_content);
        et_title = (EditText) findViewById(R.id.et_title);
        tvTitle = (TextView) findViewById(R.id.tvTitle);

        llBottomContainer = (LinearLayout) findViewById(R.id.llBottomContainer);
        ib_picture = (ImageButton) findViewById(R.id.ib_picture);
        ibKeyboard = (ImageButton) findViewById(R.id.ibKeyboard);
        ibAt = (ImageButton) findViewById(R.id.ibAt);

        ibSetting = (ImageButton) findViewById(R.id.ibSetting);
        llActionBottom = (LinearLayout) findViewById(R.id.llActionBottom);
        tvAnonymousState = (TextView) findViewById(R.id.tvAnonymousState);
        ibAnonymous = (ImageButton) findViewById(R.id.ibAnonymous);

        tvCancel = (TextView) findViewById(R.id.tvCancel);
        tvNext = (TextView) findViewById(R.id.tvNext);
        tvCancel.setOnClickListener(this);
        tvNext.setOnClickListener(this);

        ibSetting.setOnClickListener(this);
        ibAnonymous.setOnClickListener(this);
        ibKeyboard.setOnClickListener(this);
        ibAt.setOnClickListener(this);

        ib_picture.setOnClickListener(this);
        imagePicker = ImagePickerManager.ins();
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(false);
        if (android.os.Build.MODEL.contains("HM NOTE")) {
            imagePicker.setShowCamera(false);
        }

        lsContent = (LSWebView) findViewById(R.id.lsContent);
        lsContent.loadUrl("https://www.urmoli.com/webHtml/ml_editor/editor.html");
        lsContent.setFocusableInTouchMode(true);

        lsContent.setFocusable(true);

        /**
         * 模拟事件以解决H5光标的bug
         */
        et_title.performClick();

        et_title.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    llBottomContainer.setVisibility(View.GONE);
                } else {
                    llBottomContainer.setVisibility(View.VISIBLE);
                }
            }
        });
        lsContent.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    llBottomContainer.setVisibility(View.VISIBLE);
                } else {
                    llBottomContainer.setVisibility(View.GONE);
                }
            }
        });

        ib_picture = (ImageButton) findViewById(R.id.ib_picture);
        ibKeyboard = (ImageButton) findViewById(R.id.ibKeyboard);
        initTitleChange();

        mKeyboardChangeListener = new KeyboardChangeListener(this);
        mKeyboardChangeListener.setKeyBoardListener(this);

        lsContent.setOnOpenUrlListener(new LSWebView.OnOpenUrlListener() {
            @Override
            public void onOpenUrl(String url) {

            }

            @Override
            public void showLoadingLayout() {

            }

            @Override
            public void hideLoadingLayout() {
                int height = (int) ((float) RT.getScreenHeight() / RT.getDensity()) - 300;
                lsContent.loadUrl("javascript:setDivHeight('" + height + "')");
                if (isEditProblem) {
                    String content = problem.getContent();
                    lsContent.loadUrl("javascript:htmls('" + content + "')");
                } else {
                    String hint = "添加问题描述，更快获得回答";
                    lsContent.loadUrl("javascript:cue('" + hint + "')");
                }
            }

            @Override
            public void onReceivedError() {

            }
        });

        if (getIntent().hasExtra("isEditProblem")) {
            isEditProblem = getIntent().getBooleanExtra("isEditProblem", false);
            problem = (Problem) getIntent().getSerializableExtra(AppKey.PROBLEM);
            et_title.setText(problem.getTitle());
            et_title.setSelection(et_title.getText().toString().length());

            problem = (Problem) getIntent().getSerializableExtra(AppKey.PROBLEM);
            String content = problem.getContent();
            lsContent.loadUrl("javascript:htmls('" + content + "')");
            isAnonymous = problem.getIsAnonymous() == 1 ? true : false;
            updateAnonymousUI();
        }
        EventManager.ins().registListener(EventTag.ON_PROBLEM_ADD, eventListener);
        EventManager.ins().registListener(EventTag.ON_GET_CONTENT, eventListener);
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ON_PROBLEM_ADD:
                    finish();
                    break;
                case EventTag.ON_GET_CONTENT:
                    InputContent values = (InputContent) dataobj;
                    String content = values.getContent();
                    String headImage = values.getHeadImage();
                    String inputText = values.getText();
                    String title = et_title.getText().toString();
                    if (TextUtils.isEmpty(title)) {
                        return;
                    } else {
                        if (!title.trim().endsWith("?")) {
                            title += "?";
                        }
                    }
                    if (StringUtil.getTotalBytes(title) < MIN_TITLE_BYTE) {
                        ToastUtil.showToast("标题不能低于四个字");
                        return;
                    }
                    if (TextUtils.isEmpty(inputText)) {
                        ToastUtil.showToast("问题描述不能为空！");
                        return;
                    }
                    if (inputText.length() > 500) {
                        ToastUtil.showToast("问题描述不能超过500字");
                        return;
                    }
                    if (isEditProblem) {
                        problem.setContent(content);
                        problem.setTitle(title);
                        problem.setImage(headImage);
                        if (isAnonymous) {
                            problem.setIsAnonymous(1);
                        } else {
                            problem.setIsAnonymous(0);
                        }
                        SelectTopicActivity.startWithEditProblem(AskQuestionActivity.this, problem);
                    } else {
                        Intent intentSelectSubject = new Intent(AskQuestionActivity.this, SelectTopicActivity.class);
                        intentSelectSubject.putExtra(AppKey.QUESTION_TITLE, title);
                        intentSelectSubject.putExtra(AppKey.QUESTION_CONTENT, content);
                        intentSelectSubject.putExtra(AppKey.QUESTION_HEAD_IMAGE, headImage);
                        intentSelectSubject.putExtra(AppKey.IS_ANONYMOUS, isAnonymous);
                        startActivityForResult(intentSelectSubject, AppKey.REQUEST_CODE_PROBLEM_CONTENT);
                    }
                    break;
            }
        }
    };

    public void updateAnonymousUI() {
        if (isAnonymous) {
            ibAnonymous.setImageResource(R.drawable.ic_close_anonymous);
            tvAnonymousState.setText("关闭匿名");
        } else {
            ibAnonymous.setImageResource(R.drawable.ic_open_anonymous);
            tvAnonymousState.setText("启用匿名");
        }
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.ON_PROBLEM_ADD, eventListener);
        EventManager.ins().removeListener(EventTag.ON_GET_CONTENT, eventListener);
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    boolean isKeyboardShow = false;

    private int keyboardHeight;

    @Override
    public void onKeyboardChange(boolean isShow, int keyboardHeight) {
        int height = (int) ((float) (RT.getScreenHeight() - 100 - keyboardHeight) / RT.getDensity());

        lsContent.loadUrl("javascript:setDivHeight('" + height + "')");
        isKeyboardShow = isShow;
        if (!isShow) {
            ibKeyboard.setImageResource(R.drawable.ic_keybord_show);
        } else {
            llActionBottom.setVisibility(View.GONE);
            if (keyboardHeight > 140) {
                this.keyboardHeight = keyboardHeight;
            }
            ibKeyboard.setImageResource(R.drawable.ic_keybord_hide);
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvCancel:
                SoftKeyboardUtil.hideSoftKeyboard(et_title);
                onBackPressed();
                break;
            case R.id.ibKeyboard:
                if (isKeyboardShow) {
                    SoftKeyboardUtil.hideSoftKeyboard(et_title);
                } else {
                    SoftKeyboardUtil.showSoftKeyboard(et_title);
                }
                break;
            case R.id.ib_picture:
                lsContent.loadUrl("javascript:ZSSEditor.restoreRange()");
                SoftKeyboardUtil.hideSoftKeyboard(lsContent);
                imagePicker.gallerySelectedPic(this);
                break;
            case R.id.ibSetting:
                if (View.GONE == llActionBottom.getVisibility()) {
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, keyboardHeight);
                    llActionBottom.setLayoutParams(params);
                    llActionBottom.setVisibility(View.VISIBLE);
                    SoftKeyboardUtil.hideSoftKeyboard(lsContent);
                } else {
                    SoftKeyboardUtil.showSoftKeyboard(lsContent);
                    llActionBottom.setVisibility(View.GONE);
                }
                break;
            case R.id.ibAnonymous:
                if (isAnonymous) {
                    isAnonymous = false;
                    ibAnonymous.setImageResource(R.drawable.ic_close_anonymous);
                    tvAnonymousState.setText("关闭匿名");
                    ToastUtil.showToast("已关闭匿名");
                } else {
                    isAnonymous = true;
                    ibAnonymous.setImageResource(R.drawable.ic_open_anonymous);
                    tvAnonymousState.setText("启用匿名");
                    ToastUtil.showToast("已启用匿名");
                }
                break;
            case R.id.tvNext:
                lsContent.loadUrl("javascript:getInputContents()");
                if (ClickUtil.isFastDoubleClick()) return;
//                String title = et_title.getText().toString();
//                if (TextUtils.isEmpty(title)) {
//                    return;
//                } else {
//                    if (!title.trim().endsWith("?")) {
//                        title += "?";
//                    }
//                }
//                if (StringUtil.getTotalBytes(title) < MIN_TITLE_BYTE) {
//                    ToastUtil.showToast("标题不能低于四个字");
//                    return;
//                }
////                SoftKeyboardUtil.hideSoftKeyboard(et_title);
//                if (isEditProblem) {
//                    problem.setTitle(title);
//                    AnswerActivity.startWithEditProblem(AskQuestionActivity.this, problem);
//                } else {
//                    Intent intent = new Intent(AskQuestionActivity.this, AnswerActivity.class);
//                    intent.putExtra(AppKey.IS_ANSWER, false);
//                    intent.putExtra(AppKey.QUESTION_TITLE, title);
//                    startActivityForResult(intent, REQUEST_CODE_PROBLEM_TILTE);
//                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
//            if (AppKey.REQUEST_CODE_PROBLEM_TILTE == requestCode) {
//                setResult(RESULT_OK);
//                finish();
//            }
            if (requestCode == AppKey.REQUEST_CODE_PROBLEM_CONTENT) {
                setResult(RESULT_OK);
                finish();
            }
        } else if (resultCode == ImagePickerManager.RESULT_CODE_ITEMS) {
            if (data == null) {
                return;
            }
            if (requestCode == ImagePickerManager.RESULT_CODE_GALLERY) {//从图库返回
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePickerManager.EXTRA_RESULT_ITEMS);
                for (int i = 0; i < images.size(); i++) {
                    ImageItem item = images.get(i);
                    insertBitmap(item.path);
                }
            }
        } else if (requestCode == ImagePickerManager.REQUEST_CODE_TAKE) {
            //发送广播通知图片增加了
            ImagePickerManager.galleryAddPic(this, imagePicker.getTakeImageFile());
            ImageItem imageItem = new ImageItem();
            imageItem.path = imagePicker.getTakeImageFile().getAbsolutePath();
            imagePicker.clearSelectedImages();
            imagePicker.addSelectedImageItem(0, imageItem, true);
            insertBitmap(imagePicker.getTakeImageFile().getAbsolutePath());
        }
    }

    /**
     * 添加图片到富文本剪辑器
     *
     * @param imagePath
     */
    private void insertBitmap(final String imagePath) {
        showLoadingDialog();
        API_App.ins().uploadData(TAG, imagePath, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                hideLoadingDialog();
                if (errCode == ResponseResult.ResultStatus.OK) {
                    UploadResult result = new Gson().fromJson(resultValue, UploadResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                        String url = result.getRes().getHashmap().getImgurl();
                        lsContent.loadUrl("javascript:ZSSEditor.insertImage('" + url + "')");
                    }
                } else {
                    DLOG.e(TAG, errMsg);
                }
                return false;
            }
        });

    }

    private final int MAX_TITLE_BYTE = 2 * 50;
    public String currentDes;
    private int indexDes;
    public String titleStr;

    /**
     * 监听标题输入
     */
    private void initTitleChange() {
        et_title.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (StringUtil.getTotalBytes(et_title.getText().toString().trim()) <= MAX_TITLE_BYTE) {
                    currentDes = et_title.getText().toString().trim();
                }
                if (!StringUtil.checkEmojText(et_title.getText().toString().trim())) {
                    indexDes = et_title.getSelectionStart();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String dexChange = et_title.getText().toString().trim();
//                if (dexChange.contains("...")) {
//                    return;
//                }
                if (TextUtils.isEmpty(dexChange)) {
                    tvNext.setEnabled(false);
//                    hideSearchFragment();
                } else {
                    tvNext.setEnabled(true);
//                    showSearchFragment(dexChange);
                }
                if (StringUtil.checkEmojText(dexChange)) {
                    ToastUtil.showToast(RT.getString(R.string.disable_emoji));
                    et_title.setText(StringUtil.replaceEmojText(dexChange));
                    et_title.setSelection(indexDes);
                    return;
                }
                titleStr = et_title.getText().toString().trim();
                int currentLength = StringUtil.getTotalBytes(titleStr);
                tvTitle.setVisibility(View.VISIBLE);

                if (currentLength > MAX_TITLE_BYTE) {
                    et_title.setText(dexChange.substring(0, MAX_TITLE_BYTE / 2));
                    et_title.setSelection(et_title.getText().length());
                    ToastUtil.showToast(RT.getString(R.string.txt_info_title));
                } else {
                    tvTitle.setText(getString(R.string.leftCount, String.valueOf((MAX_TITLE_BYTE - currentLength) / 2)));
                }
            }
        });
    }

//    SearchRecommandFragment searchRecommandFragment = new SearchRecommandFragment();

    /**
     * 显示搜索页面
     *
     * @param keyWord
     */
//    private void showSearchFragment(String keyWord) {
//        FragmentManager fm = getSupportFragmentManager();
//        FragmentTransaction transaction = fm.beginTransaction();
//        searchRecommandFragment.doSearch(keyWord);
//        transaction.replace(R.id.flSearchContainer, searchRecommandFragment);
//        transaction.commitAllowingStateLoss();
//    }

//    private void hideSearchFragment() {
//        if (searchRecommandFragment.isAdded() && searchRecommandFragment.isVisible(this)) {
//            FragmentManager fm = getSupportFragmentManager();
//            FragmentTransaction transaction = fm.beginTransaction();
//            transaction.remove(searchRecommandFragment);
//            transaction.commitAllowingStateLoss();
//        }
//    }

}
